#include <Adafruit_HX711.h>
#include <Adafruit_NeoPixel.h>
#include <Arduino.h>
#include <vector>

#define WS2812_PIN 2 // 灯带引脚
#define WS2812_NUM 2 // 灯的数量
#define Bright 255   // 灯珠亮度
#define Delay_T 10   // 延时时间

#define HX711_SCK 4 // hx711 时钟线
#define HX711_DT 3  // hx711 数据线

// 使用RGB模式控制ws2812类型灯带
Adafruit_NeoPixel strip(WS2812_NUM, WS2812_PIN, NEO_GRB + NEO_KHZ800);
Adafruit_HX711 hx711(HX711_DT, HX711_SCK);
std::vector<int32_t> heighth;
int32_t avarage;

/**
 * @brief  设置第n到m个LED灯
 * @param  Start，开始的灯珠
 * @param  Stop，结束的灯珠
 * @param  Color, LED的颜色
 * @retval 无
 **/

void ws2812_colar_bilt(uint8_t r, uint8_t g, uint8_t b) //
{
    //--------灯珠颜色------起始灯珠-------结束灯珠-------//
    strip.fill(strip.Color(r, g, b), 0, WS2812_NUM);
    strip.show();
    delay(Delay_T);
}

/**
 * @brief  WS2812的初始化
 * @param  无
 * @retval 无
 **/
void ws2812_Init(void)
{
    // Adafruit_NeoPixel strip(LED_NUM, LED_PIN, NEO_GRB + NEO_KHZ800);

    strip.begin();               // 初始化灯带
    strip.setBrightness(Bright); // 设置亮度数值S(max=255)
    strip.show();                // 灯带显示
    delay(Delay_T);
    ws2812_colar_bilt(255, 0, 0);
}

int32_t get_avarage()
{
    int32_t sum = 0;
    for (uint8_t t = 0; t < 5; t++)
    {
        sum += heighth[t];
    }
    sum /= 5;
    return sum;
}

void hx711_Init()
{
    // Initialize the HX711
    hx711.begin();

    // read and toss 3 values each
    Serial.println("Tareing....");
    for (uint8_t t = 0; t < 5; t++)
    {
        hx711.tareA(hx711.readChannelRaw(CHAN_A_GAIN_128));
        hx711.tareA(hx711.readChannelRaw(CHAN_A_GAIN_128));
        hx711.tareB(hx711.readChannelRaw(CHAN_B_GAIN_32));
        hx711.tareB(hx711.readChannelRaw(CHAN_B_GAIN_32));
    }
    for (uint8_t t = 0; t < 5; t++)
    {
        heighth.push_back(hx711.readChannelBlocking(CHAN_A_GAIN_128));
    }
    avarage = get_avarage();
    ws2812_colar_bilt(0, 0, 0);
}

int32_t get_heighth()
{
    heighth.erase(heighth.begin());
    heighth.push_back(hx711.readChannelBlocking(CHAN_A_GAIN_128));
    return get_avarage();
}

void control_led()
{
    int i = 0;
    int32_t res = 0;
    while (i <= 2)
    {
        res = get_heighth();
        Serial.printf("last:%d, current:%d", avarage, res);
        Serial.println();
        if (res > avarage)
        {
            if (res - avarage > 400)
            {
                ws2812_colar_bilt(255, 255, 255);
            }
        }
        else if (res <= avarage)
        {
            if (avarage - res > 400)
            {
                ws2812_colar_bilt(0, 0, 0);
            }
        }
        i++;
        delay(300);
    }
    avarage = res;
}

void setup()
{
    Serial.begin(115200);
    Serial.println("start");
    ws2812_Init();
    hx711_Init();
}

void loop() { control_led(); }
